/**
 * Created by Pasturn on 16/11/12.
 */
var chat = angular.module('chat', ['ui.router']);

chat.config(['$provide', '$stateProvider', function($provide, $stateProvider) {
    "use strict";
    var baseUrl = 'http://118.244.229.132:8081/IM/api/v1.0/'
    var appkey = 'p5tvi9dstpyf4'; //3argexb6re3de e5t4ouvptoo9a
    var userId = 'a6'

    $provide.provider("appconfig", function(){
        this.$get = function () {
            return {
                getBaseUrl: function () {
                    return baseUrl
                },
                getAppKey: function () {
                    return appkey
                },
                getUserId: function () {
                    return userId
                }
            }
        }
    })

    $stateProvider
        .state('main', {
            url: '/',
            templateUrl: './assets/tpl/main.htm',
            controller: 'mainController'
        })
}])

chat.service('mainServer', ['$http', '$q', 'appconfig', function ($http, $q, appconfig) {
    "use strict";

}])

chat.service('UserServer', ['$http', '$q', 'appconfig', function ($http, $q, appconfig) {
    "use strict";
    var service = {
        //注册
        register: function (username, password) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'user/register',
                method: 'GET',
                params: {
                    username: username,
                    password: password
                }
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
        //登录
        login: function (account, password) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'user/login',
                method: 'GET',
                params: {
                    account: account,
                    password: password
                }
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
        //注销
        loginout: function (userid) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'user/' + userid + '/loginout',
                method: 'GET'
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
        //设置用户头像
        setPortrait: function (userid, url) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'user/' + userid + '/set_portrait_uri',
                method: 'GET'
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
        //获取Token
        getToken: function (userid) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'user/' + userid + '/token',
                method: 'GET'
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
        //获取用户群组
        getGroups: function (userid) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'user/' + userid + '/groups',
                method: 'GET'
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
        //设置群组置顶
        setTopGroup: function (userid, groupid) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'user/' + userid + '/setgrouptop',
                method: 'GET',
                params: {
                    groupid: groupid,
                    istop: 1
                }
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
        //获取用户信息
        getUserInfo: function (userid) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'user/' + userid,
                method: 'GET'
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
        //根据用户名查找用户
        searchUser: function (username) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'user/find/' + username,
                method: 'GET'
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
    }
    return service
}]);

chat.service('GroupServer', ['$http', '$q', 'appconfig', function ($http, $q, appconfig) {
    "use strict";
    var service = {
        //创建群组
        createGroup: function (userids, groupname, groupmemo) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'group/create',
                method: 'GET',
                params: {
                    userids: userids,
                    groupname: groupname,
                    groupmemo: groupmemo,
                }
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
        //加入群组
        joinGroup: function (groupid, userids) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'group/' + groupid + '/join',
                method: 'GET',
                params: {
                    userids: userids
                }
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
        //退出群组
        quitGroup: function (groupid, userids) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'group/' + groupid + '/quit',
                method: 'GET',
                params: {
                    userids: userids
                }
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
        //解散群组
        destroyGroup: function (groupid) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'group/' + groupid + '/destroy',
                method: 'GET'
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
        //设置群管理员
        setGroupAdmin: function (groupid, userid) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'group/' + groupid + '/setadmin/' + userid,
                method: 'GET'
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
        //设置群是否可以加人
        setGroupIsOpen: function () {
            return
        },
        //设置用户群消息
        setGroupNotify: function (groupid, isnotify) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'group/' + groupid + '/setnotify',
                method: 'GET',
                params: {
                    userid: groupid,
                    isnotify: isnotify
                }
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
        //设置群名称和简介
        setGroupInfo: function (groupname, groupmemo) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'group/' + groupid + '/setgroupinfo',
                method: 'GET',
                params: {
                    userid: groupname,
                    isnotify: groupmemo
                }
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
        //获取群的用户列表
        getGroupUsers: function (groupid) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'group/' + groupid + '/users',
                method: 'GET'
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
        //获取群的用户详细信息
        getGroupUserInfo: function (groupid) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'group/' + groupid + '/usersinfo',
                method: 'GET'
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
        getGroupInfo: function (groupid) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'group/' + groupid,
                method: 'GET',
                params: {
                    groupid: groupid
                }
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
        //获取所有群
        getAllGroups: function () {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'group/all',
                method: 'GET'
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        },
        //根据群名字查找群
        searchGroup: function (groupname) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'group/find/groupname',
                method: 'GET'
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        }
    }
    return service
}])

chat.service('DepServer', ['$http', '$q', 'appconfig', function ($http, $q, appconfig) {
    "use strict";
    var service = {
        //获取所有组织机构和人员信息
        getAllDepartment: function () {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'dep/all',
                method: 'GET'
            }).success(function(data, header, config, status){
                defer.resolve(data)
            }).error(function(data, header, config, status){
                defer.reject(data)
            })
            return defer.promise
        },
        //获取该组织机构下的员工列表
        getEmployee: function (departmentId) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'dep/' + departmentId + '/emps',
                method: 'GET'
            }).success(function(data, header, config, status){
                defer.resolve(data)
            }).error(function(data, header, config, status){
                defer.reject(data)
            })
            return defer.promise
        },
        //获取该组织机构下的组织机构列表
        getDepartmentList: function (departmentId) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'dep/' + departmentId + '/deps',
                method: 'GET'
            }).success(function(data, header, config, status){
                defer.resolve(data)
            }).error(function(data, header, config, status){
                defer.reject(data)
            })
            return defer.promise
        },
        //根据departmentName搜索部门
        searchDepartment: function (departmentName) {
            var defer = $q.defer();
            $http({
                url: appconfig.getBaseUrl() + 'dep/find/' + departmentName,
                method: 'GET'
            }).success(function (data, header, config, status) {
                defer.resolve(data)
            }).error(function (data, header, config, status) {
                defer.reject(data)
            })
            return defer.promise
        }
    }
    return service
}]);

chat.factory('ConversationServer', ['$q', '$rootScope', function($q, $rootScope){
    "use strict";
    var conversationServer = {};
        conversationServer.atMesssageCache = {};
        conversationServer.historyMessagesCache = {};
        conversationServer.conversationMessageList = [];
        conversationServer.conversationMessageListShow = [];
        conversationServer.pullMessageTime = null;
        conversationServer.remainMessageCount = 5;
        conversationServer.withDrawMessageCache = {};

    //function compareDateIsAddSpan(first, second) {
    //    if (Object.prototype.toString.call(first) == "[object Date]" && Object.prototype.toString.call(second) == "[object Date]") {
    //        var pre = first.toString();
    //        var cur = second.toString();
    //        return pre.substring(0, pre.lastIndexOf(":")) != cur.substring(0, cur.lastIndexOf(":"))
    //    } else {
    //        return false;
    //    }
    //}
    //
    //function getHistory(id, type, lastTime, count) {
    //    var defer = $q.defer()
    //    var conver = type;
    //    var currentConversationTargetId = id
    //
    //    if(!conversationServer.historyMessagesCache[conver + '_' + currentConversationTargetId]) {
    //        conversationServer.historyMessagesCache[conver + '_' + currentConversationTargetId] = []
    //    }
    //    try {
    //        RongIMSDKServer.getHistoryMessages(+conver, currentConversationTargetId, lastTime, count)
    //            .then(function(data){
    //                var has = data.has, list = data.data
    //                var msglen = list.length;
    //                if(msglen > 0) {
    //                    conversationServer.pullMessageTime = list[msglen - 1].sentTime;
    //                }
    //                var _withDrawMsg = conversationServer.withDrawMessageCache[conver + '_' + currentConversationTargetId]
    //                while (msglen--) {
    //                    var msgsdk = list[msglen];
    //                    if(_withDrawMsg && _withDrawMsg.indexOf(msgsdk.messageUID)>-1) {
    //                        continue
    //                    }
    //                    switch (msgsdk.messageType) {
    //                        case RongIMClient.MessageType.ContactNotificationMessage:
    //                            //历史邀请消息不做处理
    //                            break;
    //                        case RongIMClient.MessageType.TextMessage:
    //                        case RongIMClient.MessageType.VoiceMessage:
    //                        case RongIMClient.MessageType.LocationMessage:
    //                        case RongIMClient.MessageType.ImageMessage:
    //                        case RongIMClient.MessageType.RichContentMessage:
    //                        case RongIMClient.MessageType.FileMessage:
    //                            var item = webimmodel.Message.convertMsg(msgsdk);
    //                            if (item) {
    //                                unshiftHistoryMessages(currentConversationTargetId, conver, item);
    //                            }
    //                            break;
    //                        case RongIMClient.MessageType.GroupNotificationMessage:
    //                            if (msgsdk.objectName == "RC:GrpNtf") {
    //                                var item = webimmodel.Message.convertMsg(msgsdk);
    //                                if (item) {
    //                                    conversationServer.asyncConverGroupNotifition(msgsdk, item);
    //                                    unshiftHistoryMessages(currentConversationTargetId, conver, item);
    //                                }
    //                            }
    //                            break;
    //                        case RongIMClient.MessageType.UnknownMessage:
    //                            if (msgsdk.objectName == "RC:GrpNtf") {
    //                                var item = RongIMClient.Message.convertMsg(msgsdk);
    //                                if (item) {
    //                                    conversationServer.asyncConverGroupNotifition(msgsdk, item);
    //                                    unshiftHistoryMessages(currentConversationTargetId, conver, item);
    //                                }
    //                            }
    //                            break;
    //                        case RongIMClient.MessageType.RecallCommandMessage:
    //                            if (msgsdk.objectName == "RC:RcCmd") {
    //                                // var item = webimmodel.Message.convertMsg(msgsdk);
    //                                // if (item) {
    //                                //     conversationServer.delWithDrawMessage(item.senderUserId, item.conversationType, msgsdk.messageUId);
    //                                //     unshiftHistoryMessages(currentConversationTargetId, conver, item);
    //                                // }
    //                                // conversationServer.addWithDrawMessageCache(item.senderUserId, item.conversationType, msgsdk.messageUId);
    //                            }
    //                            break;
    //                        case RongIMClient.MessageType.InformationNotificationMessage:
    //                            var item = webimmodel.Message.convertMsg(msgsdk);
    //                            if (item) {
    //                                unshiftHistoryMessages(currentConversationTargetId, conver, item);
    //                            }
    //                            break;
    //                        case RongIMClient.MessageType.DiscussionNotificationMessage:
    //                            if (msgsdk.objectName == "RC:DizNtf") {
    //
    //                            }
    //                            break;
    //                        default:
    //                            console.log("此消息类型未处理：" + msgsdk.messageType);
    //                            break;
    //                    }
    //                }
    //                var addtime = conversationServer.historyMessagesCache[conver + '_' + currentConversationTargetId][0]
    //                if (addtime && addtime.panelType != RongIMClient.panelType.Time) {
    //                    unshiftHistoryMessages(currentConversationTargetId, conver, new RongIMClient.TimePanl(conversationServer.historyMessagesCache[conver + "_" + currentConversationTargetId][0].sentTime))
    //                }
    //                defer.resolve(has)
    //            }, function (err) {
    //                defer.reject(err)
    //            });
    //    } catch (err) {
    //        console.log("SDK error" + err)
    //    }
    //    return defer.promise
    //}
    //
    //function unshiftHistoryMessage(id, type, item) {
    //    var arr = conversationServer.historyMessagesCache[type + '_' + id] || []
    //    if (arr[0] && item.messageUId && item.messageUId === arr[0].messageUId) {
    //        return;
    //    }
    //
    //    if (arr[0] && arr[0].sentTime && arr[0].panelType != RongIMClient.PanelType.Time && item.sentTime) {
    //        if (compareDateIsAddSpan(arr[0].sentTime, item.sentTime)) {
    //            arr.unshift(new RongIMClient.TimePanl(arr[0].sentTime));
    //        }
    //    }
    //    //messageAddUserInfo(item);
    //    arr.unshift(item);
    //}
    function addHistoryMessage(id, type, item) {
        var arr = conversationServer.historyMessagesCache[type + '_' + id] || [];

        //if (arr[arr.length - 1] && arr[arr.length -1].panelType != RongIMClient.panelType.Time && arr[arr.length - 1].sendTime && item.sendTime ) {
        //    if (compareDateIsAddSpan(arr[arr.length - 1].sentTime, item.sentTime)) {
        //        arr.push(new RongIMClient.TimePanl(item.sendTime));
        //    }
        //}
       //广播数据
        $rootScope.$broadcast("msg_in",item);
       // $rootScope.$broadcast("conversation",item.targetId);
        //$rootScope.$broadcast("conversation",item);
        /*console.info($rootScope)
        console.info(item)
        console.info($scope)*/
        conversationServer.conversationMessageListShow.push(item);


    }

    //conversationServer.unshiftHistoryMessage = unshiftHistoryMessage;
    //conversationServer.getHistory = getHistory
    conversationServer.addHistoryMessage = addHistoryMessage;

    return conversationServer
}])


chat.service('RongIMSDKServer', ['$q','ConversationServer', function ($q, ConversationServer) {
    "use strict";
    var service = {
        init: function (appkey) {
            RongIMLib.RongIMClient.init(appkey)
        },
        connect: function (token) {
            var defer = $q.defer()
            RongIMLib.RongIMClient.connect(token, {
                onSuccess: function (data) {
                    defer.resolve(data)
                },
                onTokenIncorrect: function () {
                    defer.reject({ tokenError: true })
                },
                onError: function(errorCode) {
                    defer.reject({ errorCode: errorCode});
                    var info = '';
                    switch (errorCode) {
                        case RongIMLib.ErrorCode.TIMEOUT:
                            info = '连接超时';
                            break;
                        case RongIMLib.ErrorCode.UNKNOWN:
                            info = '未知错误';
                            break;
                        case RongIMLib.ConnectionState.UNACCEPTABLE_PROTOCOL_VERSION:
                            info = '不可接受的协议版本';
                            break;
                        case RongIMLib.ConnectionState.IDENTIFIER_REJECTED:
                            info = 'appkey不正确';
                            break;
                        case RongIMLib.ConnectionState.SERVER_UNAVAILABLE:
                            info = '服务器不可用';
                            break;
                        case RongIMLib.ConnectionState.NOT_AUTHORIZED:
                            info = '未认证';
                            break;
                        case RongIMLib.ConnectionState.REDIRECT:
                            info = '重新获取导航';
                            break;
                        case RongIMLib.ConnectionState.APP_BLOCK_OR_DELETE:
                            info = '应用已被封禁或已被删除';
                            break;
                        case RongIMLib.ConnectionState.BLOCK:
                            info = '用户被封禁';
                            break;
                    }
                    console.log("失败:" + info + errorCode);
                }
            })
            return defer.promise
        },
        setConnectionStatusListener: function () {
            return RongIMClient.setConnectionStatusListener({
                onChanged: function (status) {
                    switch (status) {
                        //链接成功
                        case RongIMLib.ConnectionStatus.CONNECTED:
                            console.log('链接成功');
                            break;
                        //正在链接
                        case RongIMLib.ConnectionStatus.CONNECTING:
                            console.log('正在链接');
                            break;
                        //重新链接
                        case RongIMLib.ConnectionStatus.DISCONNECTED:
                            console.log('断开连接');
                            break;
                        //其他设备登录
                        case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                            console.log('其他设备登录');
                            break;
                        //网络不可用
                        case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                            console.log('网络不可用');
                            break;
                    }
                }
            })
        },
        setOnReceiveMessageListener: function () {
            RongIMClient.setOnReceiveMessageListener({
                onReceived: function (message) {
                    switch(message.messageType){
                        case RongIMClient.MessageType.TextMessage:
                        case RongIMClient.MessageType.LocationMessage:
                        case RongIMClient.MessageType.RichContentMessage:
                        case RongIMClient.MessageType.ImageMessage:
                            ConversationServer.addHistoryMessage(message.targetId, message.messageType, message)
                            break;

                        case RongIMClient.MessageType.VoiceMessage:
                            // 对声音进行预加载
                            // message.content.content 格式为 AMR 格式的 base64 码
                            RongIMLib.RongIMVoice.preLoaded(message.content.content);
                            break;

                        case RongIMClient.MessageType.DiscussionNotificationMessage:
                            // do something...
                            break;

                        case RongIMClient.MessageType.InformationNotificationMessage:
                            // do something...
                            break;
                        case RongIMClient.MessageType.ContactNotificationMessage:
                            // do something...
                            break;
                        case RongIMClient.MessageType.ProfileNotificationMessage:
                            // do something...
                            break;
                        case RongIMClient.MessageType.CommandNotificationMessage:
                            // do something...
                            break;
                        case RongIMClient.MessageType.CommandMessage:
                            // do something...
                            break;
                        case RongIMClient.MessageType.UnknownMessage:
                            // do something...
                            break;
                        default:
                            break;
                            // 自定义消息
                            // do something...
                    }
                }
            })
        },
        addMessageAndOperation: function (msg) {
            var key = meg.conversationType + '_' + msg.targetId

        },
        startCustomService: function (tagetId) {
            var defer = $q.defer();
            RongIMLib.RongIMClient.getInstance().startCustomService(tagetId, {
                onSuccess: function () {
                    defer.resolve()
                },
                onError: function () {
                    defer.reject()
                }
            })
            return defer.promise
        },
        sendReadReceiptMessage: function (targetId, type) {
            var that = this
            RongIMLib.RongIMClient.getInstance()
                .getConversation(Number(type), targetId, {
                    onSuccess: function (data) {
                        if (data) {
                            var read = RongIMLib.ReadReceiptMessage
                                .obtain(data.latestMessage.messageUId,
                                data.latestMessage.sentTime, "1");

                            that.sendMessage(type, targetId, read);
                        }
                    },
                    onError: function () {}
                })
        },
        sendMessage: function(conver, targetId, content) {
            var defer = $q.defer()
            RongIMLib.RongIMClient.getInstance().sendMessage(conver, targetId, content, {
                onSuccess: function (data) {
                    defer.resolve(data);
                },
                onError: function (errorCode, message) {
                    defer.reject({errorCode: errorCode, message: message});
                    var info = '';
                    switch (errorCode) {
                        case RongIMLib.ErrorCode.TIMEOUT:
                            info = '超时';
                            break;
                        case RongIMLib.ErrorCode.UNKNOWN:
                            info = '未知错误';
                            break;
                        case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                            info = '在黑名单中，无法向对方发送消息';
                            break;
                        case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                            info = '不在讨论组中';
                            break;
                        case RongIMLib.ErrorCode.NOT_IN_GROUP:
                            info = '不在群组中';
                            break;
                        case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                            info = '不在聊天室中';
                            break;
                        default:
                            info = "";
                            break;
                    }
                    console.log('发送失败:' + info);
                }
            })
            return defer.promise
        },

        reconnect: function (callback) {
            RongIMLib.RongIMClient.reconnect(callback)
        },

        disconnect: function () {
            RongIMLib.RongIMClient.disconnect()
        },

        logout: function () {
            if (RongIMLib && RongIMLib.RongIMClient) {
                RongIMLib.RongIMClient.getInstance().logout()
            }
        },

        clearUnreadCount: function (type, targetId) {
            var defer = $q.defer();
            RongIMLib.RongIMClient.getInstance()
                .clearUnreadCount(type, targetId, {
                    onSuceess: function (data) {
                        defer.resolve(data);
                    },
                    onError: function (error) {
                        defer.reject(error)
                    }
                })
            return defer.promise
        },

        getTotalUnreadCount: function () {
            var defer = $q.defer()
            RongIMLib.RongIMClient.getInstance()
                .getTotalUnreadCount({
                    onSuccess: function(num) {
                        defer.resolve(num);
                    },
                    onError: function() {
                        defer.reject();
                    }
                });
            return defer.promise;
        },

        getConversationList: function () {
            var defer = $q.defer();
            RongIMLib.RongIMClient.getInstance()
                .getConversationList({
                    onSuccess: function(data) {
                        defer.resolve(data);
                    },
                    onError: function(error) {
                        defer.reject(error);
                    }
                }, null);
            return defer.promise;
        },

        getConversation: function (type, targetId) {
            var defer = $q.defer();
            RongIMLib.RongIMClient.getInstance().getConversation(Number(type), targetId, {
                onSuccess: function(data) {
                    defer.resolve(data);
                },
                onError: function(error) {
                    defer.reject(error);
                }
            })
            return defer.promise
        },

        updateConversation: function (con) {
            RongIMLib.RongIMClient.getInstance().updateConversation(con);
        },

        removeConversation: function (type, targetId) {
            var defer = $q.defer()
            RongIMLib.RongIMClient.getInstance()
                .removeConversation(type, targetId, {
                    onSuccess: function (data) {
                        defer.resolve(data)
                    },
                    onError: function (error) {
                        defer.reject(error)
                    }
                })
            return defer.promise
        },

        getHistoryMessages: function (type, targetId) {
            var defer = $q.defer()
            RongIMLib.RongIMClient.getInstance()
                .getHistoryMessages(type, targetId, {
                    onSuccess: function(data, has) {
                        defer.resolve({
                            data: data,
                            has: has
                        })
                    },
                    onError: function (error) {
                        defer.reject(error)
                    }
                })
            return defer.promise
        },

        getDraft: function (type, targetId) {
            return RongIMLib.RongIMClient.getInstance()
                .getTextMessageDraft(type, targetId)
        },

        setDraft: function (type, targetId) {
            return RongIMLib.RongIMClient.getInstance()
                .saveTextMessageDraft(type, targetId)
        },

        clearDraft: function (type, targetId) {
            return RongIMLib.RongIMClient.getInstance()
                .clearTextMessageDraft(type, targetId)
        }
    };
    return service
}]);


chat.run(['$http', 'RongIMSDKServer', 'UserServer', 'appconfig', function ($http, RongIMSDKServer, UserServer, appconfig) {
    "use strict";
    var userId
    console.log(UserServer)
    UserServer.login('test1', 'test1')
        .then(function success(data) {
            userId = data.result.userid;
            UserServer.getToken(userId)
                .then(function success (data) {
                    var token = data.result.token
                    RongIMSDKServer.init(appconfig.getAppKey())
                    RongIMSDKServer.connect(token)
                    RongIMSDKServer.setConnectionStatusListener()
                    RongIMSDKServer.setOnReceiveMessageListener()
                })
                .catch(function error (data) {
                    console.log(data)
                })
        })
        .catch(function error(data) {
        console.log(data)
        })
    }
])

chat.controller('mainController', ['$scope', '$http', 'DepServer', 'GroupServer', 'RongIMSDKServer', 'appconfig',
    function($scope, $http, DepServer, GroupServer, RongIMSDKServer, appconfig){
    "use strict";
    DepServer.getAllDepartment()
        .then(function success (data) {
            $scope.$broadcast('contactlist', data.result)
        })
        .catch(function error (error) {
            console.log(error)
        });
    GroupServer.getAllGroups()
        .then(function success (data) {
            $scope.$broadcast('grouplist', data.result)
        })
        .catch(function error (error){
            console.log(error)
        })
    $scope.$on('contact', function(e, data) {
        $scope.$broadcast('conversation', data)
    })
}])

chat.controller('contactController', ['$scope', '$rootScope',
    function($scope, $rootScope){
    "use strict";
    $scope.$on('contactlist', function(e, data) {
        $scope.contactlist = data
    });
    $scope.$on('grouplist', function(e, data) {
        console.log(data)
        $scope.grouplist = data
    })
    //$scope.contacts = $rootScope.contacts
    $scope.onPanel = 'contact'
    $scope.selectPanel = function (panel) {
        $scope.onPanel = panel
    }
    $scope.selectContact = function (userid) {
        $scope.$emit('contact', userid)
    }
}])

chat.controller('chatroomController', ['$scope', '$http', 'UserServer','ConversationServer', 'RongIMSDKServer', 'appconfig',
    function($scope, $http, UserServer, ConversationServer, RongIMSDKServer, appconfig){
    "use strict";
    $scope.targetId = null;
    $scope.messageList = [];
    console.info($scope)
    $scope.sendMessage = function () {
    	console.info($scope)
        var msg = new RongIMLib.TextMessage({content: $scope.message, extra: "附加信息"});
        var conversationtype = RongIMLib.ConversationType.PRIVATE;
        var targetId = $scope.targetId
        RongIMSDKServer.sendMessage(conversationtype, targetId, msg)
            .then(function success(data) {
            	console.info($scope);
                $scope.message = "";
                console.info(data)
                data.senderUserName=$scope.targetInfo.username;
                $scope.messageList.push(data);
               // $scope.$apply();
            })
            .catch(function error(data) {
                console.log(data)
            })
    }
    
    $scope.$on('msg_in',function(e,data){
    	 UserServer.getUserInfo(data.targetId)
    	 	.then(function success(result){
    	 		data.senderUserName=result.result.username
    	 		$scope.messageList.push(data);
    	 	})
    })
    
    $scope.$on('conversation', function (e, data) {
        $scope.targetId = data;
        UserServer.getUserInfo(data)
            .then(function success (data) {
                $scope.targetInfo = data.result
                console.log(ConversationServer.conversationMessageListShow)
                $scope.$watch(ConversationServer.conversationMessageListShow, function(newValue, oldValue, scope) {
                   //console
                	console.info(ConversationServer.conversationMessageListShow)
                	if(newValue){
                		$scope.messageList.push(newValue)
                	}
                    console.log(newValue, oldValue, scope)
                })
            })
            .catch(function error (data) {
                console.log(data)
            })


    })

}])